import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useRequest } from 'umi';
import { Row, Col, Menu, Card, Popover, Tabs, Form, Input, Button, message } from 'antd';
import { AppstoreOutlined } from '@ant-design/icons';
import { SketchPicker } from 'react-color';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TabBusiness, TabColor } from '../UpdateComponents';
import { switchTheme } from './switch-theme';
import _, { get } from 'lodash';
import { getCompanyID, getPosIDs, getTenant, getThemeFontSize, getUserDepID, getUserID } from '@/utils';
import { getSystemlogoUrl } from '@/services/urlconst';

import { appendTheme, getThemeList, editTheme } from '../../service';

import cls from 'classnames';
import './index.less';

interface IcolorType {
  name: string;
  key: string;
}

interface IThemeProps {
  locationProps: Record<string, any>;
}

const Index: React.FC<IThemeProps> = (props) => {
  const [form] = Form.useForm();

  const fontValueSize: string | number | any = getThemeFontSize() ? getThemeFontSize() : 14

  const CLSNAME = 'theme-edit';
  const logoUrl = getSystemlogoUrl(getTenant());
  const title = '系统名称';

  const [colorInfo, setColor] = useState<any>({
    '@primary-color': '#1890ff',
    '@success-color': '#52c41a',
    '@warning-color': '#faad14',
    '@error-color': '#ff4d4f',
    '@layout-header-background': undefined,
  });

  const colorList: IcolorType[] = [
    {
      name: '全局主色',
      key: '@primary-color',
    },
    {
      name: '成功色',
      key: '@success-color',
    },
    {
      name: '警告色',
      key: '@warning-color',
    },
    {
      name: '错误色',
      key: '@error-color',
    },
  ];

  /** 如果是湛蓝依然主题，加头部背景色设置 */
  const colorListMemo = useMemo(() => {
    if (props?.locationProps?.state?.id == "d2844c70-3adf-4a7e-9320-2b7f6fdec5b1") {
      colorList?.push({
        name: '头部背景色',
        key: '@layout-header-background',
      })
    }
    switchTheme(colorInfo);

    return colorList
  }, [props?.locationProps?.state])

  // /** 保存字体设置 */
  // const [fontSizeInfo, setFontSizeInfo] = useState<Record<string, any>>({
  //   "@font-size-base": 14
  // })

  const onColorChange = (colorKey: any, color: any) => {
    let newColor = _.cloneDeep(colorInfo);
    newColor[colorKey] = color;
    switchTheme(newColor);
    setColor(newColor);
  }

  useEffect(() => {
    let id = props?.locationProps?.state?.id;

    if (id) {
      run();
    }
  }, [props?.locationProps?.state?.id]);

  const { data, run } = useRequest(
    () => {
      return getThemeList();
    },
    {
      manual: true,
      onSuccess: (res) => {
        let id = props?.locationProps?.state?.id;
        if (res && res?.msgFlag && id) {
          let themeList = res?.obj;

          let targetTheme = themeList?.find((item: any) => item?.id === id);

          let defaultStyle = targetTheme?.defaultStyle;

          let newColor = {
            '@primary-color': defaultStyle?.['@primary-color'] ?? '#1890ff',
            '@success-color': defaultStyle?.['@success-color'] ?? '#52c41a',
            '@warning-color': defaultStyle?.['@warning-color'] ?? '#faad14',
            '@error-color': defaultStyle?.['@error-color'] ?? '#ff4d4f',
            '@layout-header-background': defaultStyle?.['@layout-header-background'] ?? undefined,
          };

          if (props?.locationProps?.state?.id != "d2844c70-3adf-4a7e-9320-2b7f6fdec5b1") {
            delete newColor?.['@layout-header-background']
          }

          form.setFieldsValue({
            name: targetTheme?.name,
          });

          // /** 保存字体 */
          // const fontSizeStyle = {
          //   "@font-size-base": defaultStyle?.['@font-size-base'] ?? 14,
          // }

          switchTheme(newColor);
          setColor(newColor);

          // setFontSizeInfo(fontSizeStyle)
        }
      },
    },
  );

  const onSave = () => {
    form.validateFields().then((res) => {
      if (res) {
        let id = props?.locationProps?.state?.id;

        let targetTheme = data?.obj?.find((item: any) => item?.id === id);

        if (id) {
          update.run({
            id,
            name: res?.name,
            themeStyle: {
              ...colorInfo,
            },
            defaultStyle: {
              ...colorInfo,
            },
            versionNum: targetTheme?.versionNum ?? 0,
            seq: 0,
            modifyCompanyID: getCompanyID(),
            modifyDepartmentID: getUserDepID(),
            modifyPositionID: getPosIDs(),
            modifyerID: getUserID(),
          });
        } else {
          update.run({
            name: res?.name,
            isOpen: 1,
            isDefault: 0,
            // themeStyle: colorInfo,
            // defaultStyle: colorInfo,
            themeStyle: {
              ...colorInfo,
            },
            defaultStyle: {
              ...colorInfo,
            },
          });
        }
      }
    });
  };

  const update = useRequest(
    (params: any) => {
      let id = props?.locationProps?.state?.id;

      if (id) {
        return editTheme(params);
      } else {
        return appendTheme(params);
      }
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
          run();
        } else {
          message.error(res?.msg);
        }
      },
    },
  );

  // /**
  //  * 判断当前选中
  //  * @param sizeValue 
  //  * @returns 
  //  */
  // const isFontSizeBool = (sizeValue: number) => {
  //   return fontSizeInfo?.["@font-size-base"] == sizeValue
  // }

  // /**
  //  * 字体改变
  //  * @param sizeValue 
  //  */
  // const fontSizeChange = (sizeValue: number) => {
  //   /** 保存字体 */
  //   const fontSizeInfo = {
  //     "@font-size-base": sizeValue,
  //   }
  //   switchTheme(colorInfo, fontSizeInfo);
  //   setFontSizeInfo({
  //     "@font-size-base": sizeValue
  //   })
  // }

  return (
    <div className={cls(`${CLSNAME}`)} style={{ height: '100%' }}>
      {/* <Spin spinning={loading}> */}
      <Row
        className={cls(`${CLSNAME}-layout`)}
        gutter={[8, 0]}
        id="themeID"
        style={{ height: '100%' }}
      >
        <Col
          md={18}
          sm={24}
          style={{ overflowX: 'hidden', height: '100%' }}
        >
          <div className={cls(`${CLSNAME}-menu`)}>
            <div
              className={cls(`${CLSNAME}-side`)}
              style={{ background: '#1890ff' }}
            >
              <div className={cls(`${CLSNAME}-side-child`)}>
                <div className={cls(`${CLSNAME}-side-logo`)}>
                  <img src={logoUrl} />
                  <h3>{title}</h3>
                </div>
                <Menu
                  style={{
                    width: '100%',
                  }}
                  defaultSelectedKeys={['1']}
                  defaultOpenKeys={['sub1']}
                  mode="inline"
                  theme={'dark'}
                  items={[
                    {
                      label: '主菜单',
                      key: 'sub1',
                      className: 'theme-submenu-title',
                      icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                      children: [
                        {
                          key: '5',
                          label: '子菜单 1',
                          className: 'theme-submenu-title',
                          icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                        },
                        {
                          key: '6',
                          label: '子菜单 2',
                          icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                          className: 'theme-submenu-title',
                        },
                        {
                          label: '子菜单 3',
                          icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                          key: 'sub2',
                          className: 'theme-submenu-title',
                          children: [
                            {
                              key: '7',
                              label: '子菜单 3-1',
                              className: 'theme-submenu-title',
                              icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                            },
                            {
                              key: '8',
                              label: '子菜单 3-2',
                              className: 'theme-submenu-title',
                              icon: <AppstoreOutlined style={{ fontSize: fontValueSize }} />,
                            },
                          ],
                        },
                      ],
                    },
                  ]}
                />
              </div>
            </div>
            <div className={cls(`${CLSNAME}-content`)}>
              <div className={cls(`${CLSNAME}-head`)}></div>
              <div className={cls(`${CLSNAME}-tabs`)}>
                <Tabs
                  type="editable-card"
                  className={cls('theme-submenu-tabPane')}
                  hideAdd={true}
                  items={[
                    {
                      label: <span style={{ fontSize: fontValueSize }}>组件页面</span>,
                      key: 'businessComponent',
                      children: <TabBusiness />,
                    },
                    {
                      label: <span style={{ fontSize: fontValueSize }}>颜色界面</span>,
                      key: 'colorPage',
                      children: (
                        <TabColor
                          colorInfo={colorInfo}
                          colorList={colorListMemo}
                        />
                      ),
                    },
                  ]}
                />
              </div>
            </div>
          </div>
        </Col>
        <Col
          md={6}
          sm={24}
          style={{ overflowX: 'hidden', height: '100%' }}
        >
          <ScrollBarLayout style={{ padding: "0px 5px" }}>
            <Card
              title="主题设计"
              bodyStyle={{
                padding: '5px 10px',
              }}
            >
              {colorListMemo?.map((item, index) => {
                return (
                  <div
                    className={cls(`${CLSNAME}-design`)}
                    key={item.key}
                    style={{
                      marginBottom:
                        index == colorListMemo?.length - 1 ? 0 : '12px',
                    }}
                  >
                    <div className={cls(`${CLSNAME}-design-title`)}>
                      {item.name}
                    </div>
                    <Popover
                      autoAdjustOverflow
                      trigger="click"
                      overlayInnerStyle={{ padding: 0 }}
                      placement="leftTop"
                      content={
                        <SketchPicker
                          color={colorInfo?.[item.key]}
                          onChange={({ rgb }) => {
                            let rgbColor = `rgba(${rgb.r},${rgb.g},${rgb.b},${rgb.a})`;
                            onColorChange(item.key, rgbColor);
                          }}
                        />
                      }
                    >
                      <div className={cls(`${CLSNAME}-design-pop`)}>
                        <div
                          style={{
                            width: '100%',
                            height: '100%',
                            background: colorInfo?.[item.key],
                          }}
                        ></div>
                      </div>
                    </Popover>
                  </div>
                );
              })}
            </Card>

            {/* <Card
              title="字号设置"
              style={{ marginTop: '1rem' }}
              bodyStyle={{
                padding: '10px',
              }}
            >
              <Space
                className={cls(`${CLSNAME}-fontSizeLayout`)}
                direction="vertical"
              >
                <dl
                  style={{
                    fontSize: "14px"
                  }}
                  onClick={() => {
                    if (fontSizeInfo?.["@font-size-base"] != 14) {
                      fontSizeChange(14)
                    }
                  }}
                >
                  <dt>
                    默认字体（推荐）
                  </dt>
                  <MyIcon
                    type="icon-xuanzejiaobiao"
                    isTheme={isFontSizeBool(14)}
                    style={{
                      color: !isFontSizeBool(14) ? "#cbcbcb" : ""
                    }}
                  />
                </dl>

                <dl
                  style={{ fontSize: "16px" }}
                  onClick={() => {
                    if (fontSizeInfo?.["@font-size-base"] != 16) {
                      fontSizeChange(16)
                    }
                  }}
                >
                  <dt>
                    字体：中
                  </dt>
                  <dd>
                    建议您在分辨率1600以上的显示器使用
                  </dd>
                  <MyIcon
                    type="icon-xuanzejiaobiao"
                    isTheme={isFontSizeBool(16)}
                    style={{
                      color: !isFontSizeBool(16) ? "#cbcbcb" : ""
                    }}
                  />
                </dl>

                <dl
                  style={{ fontSize: "18px" }}
                  onClick={() => {
                    if (fontSizeInfo?.["@font-size-base"] != 18) {
                      fontSizeChange(18)
                    }
                  }}
                >
                  <dt>
                    字体：大
                  </dt>
                  <dd>
                    建议您在分辨率1920以上的显示器使用
                  </dd>
                  <MyIcon
                    type="icon-xuanzejiaobiao"
                    isTheme={isFontSizeBool(18)}
                    style={{
                      color: !isFontSizeBool(18) ? "#cbcbcb" : ""
                    }}
                  />
                </dl>
              </Space>
            </Card> */}

            <Card
              title="保存主题"
              style={{ marginTop: '1rem' }}
              bodyStyle={{
                padding: '10px',
              }}
            >
              <Form form={form}>
                <Form.Item
                  label="主题名称"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入主题名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入主题名称" />
                </Form.Item>
              </Form>
              <div
                style={{
                  width: '100%',
                  textAlign: 'right',
                }}
              >
                <Button
                  type="primary"
                  onClick={onSave}
                  loading={update?.loading}
                >
                  保存
                </Button>
              </div>
            </Card>
          </ScrollBarLayout>
        </Col>
      </Row>
      {/* </Spin> */}
    </div>
  );
};

export default Index;
